
#import "CalendarView.h"



@interface CalendarView()

{
    NSCalendar *gregorian;
    NSInteger _selectedMonth;
    NSInteger _selectedYear;
    CGFloat oldHeight;
}

@end
@implementation CalendarView

@synthesize enabled;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        oldHeight = frame.size.height;
        UISwipeGestureRecognizer * swipeleft=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeleft:)];
        swipeleft.direction=UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:swipeleft];
        UISwipeGestureRecognizer * swipeRight=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swiperight:)];
        swipeRight.direction=UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipeRight];
        self.calendarDate = [NSDate date];
        [self setBackgroundColor:sa_color(240, 1.0)];
        self.enabled = YES;
        
    }
    return self;
}

//对外开放扩展
-(void)extrlCell:(UIButton *)btn forYear:(NSInteger)year forMonth:(NSInteger)month forDay:(NSInteger)day{
    
    NSString *dateStr = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [format dateFromString:dateStr];
   // NSLog(@"%@-----%@----%@",dateStr,date,[NSDate date]);
    if(self.delegate!=nil && [self.delegate respondsToSelector:@selector(exterlCell:forDate:)]){
        [self.delegate exterlCell:btn forDate:date];
    }
}

- (void)drawRect:(CGRect)rect
{
    [self setCalendarParameters];
    _weekNames = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
//    _selectedDate  =components.day;
    components.day = 2;
    NSDate *firstDayOfMonth = [gregorian dateFromComponents:components];
    NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:firstDayOfMonth];
    int weekday = [comps weekday];
//      NSLog(@"components%d %d %d",_selectedDate,_selectedMonth,_selectedYear);
    weekday  = weekday - 2;
    
    if(weekday < 0)
        weekday += 7;
    
    NSCalendar *c = [NSCalendar currentCalendar];
    NSRange days = [c rangeOfUnit:NSDayCalendarUnit
                           inUnit:NSMonthCalendarUnit
                          forDate:self.calendarDate];
    
    
    
    NSInteger columns = 7;
    NSInteger monthLength = days.length;
    NSInteger remainingDays = (monthLength + weekday) % columns;//下月日期
    NSInteger cellWidth = self.frame.size.width/columns;//单元格的宽度
    int row = ((monthLength + (remainingDays >0 ? 7 - remainingDays : 0) + weekday)/7+2);
    NSInteger cellHeight = self.frame.size.height/row;//计算出单元格的高度，有可能会有8行
    if (cellHeight!=cellWidth) {
        cellHeight = cellWidth;
        self.height = cellHeight * row;
    }else{
        //self.height = oldHeight;
    }
    
    
    NSInteger originX = 0;
    NSInteger originY = 0;
    NSInteger fontSize = 14.f;
    NSInteger cellMargin = 5;
    
    //设置年月
    UIView *topBar = [[UIView alloc]initWithFrame:CGRectMake(0,originY, self.frame.size.width, cellHeight)];
    
    UIButton *lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lastBtn.frame = CGRectMake(0,0, cellWidth, cellHeight);
    [lastBtn setImage:[UIImage imageNamed:@"calendarLeftArrow.png"] forState:UIControlStateNormal];
    [lastBtn addTarget:self action:@selector(lastMonth) forControlEvents:UIControlEventTouchUpInside];
    [topBar addSubview:lastBtn];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(6*cellWidth,0, cellWidth, cellHeight);
    [nextBtn setImage:[UIImage imageNamed:@"calendarRightArrow.png"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextMonth) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:fontSize]];
    [topBar addSubview:nextBtn];
   

    
    UILabel *titleText = [[UILabel alloc]initWithFrame:CGRectMake(self.bounds.size.width/4,0, self.bounds.size.width/4*2, cellHeight)];
    titleText.backgroundColor = [UIColor clearColor];
    titleText.textAlignment = TEXT_ALIGNMENT_CENTER;
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"M月yyyy年"];
    NSString *dateString = [[format stringFromDate:self.calendarDate] uppercaseString];
    [titleText setText:dateString];
    [titleText setFont:[UIFont fontWithName:@"Helvetica-Bold" size:fontSize]];
    [titleText setTextColor:sa_color(50, 1.0)];
    [topBar addSubview:titleText];
    
    [self addSubview:topBar];
    
    //设置星期标题
    for (int i =0; i<_weekNames.count; i++) {
        UIButton *weekNameLabel = [UIButton buttonWithType:UIButtonTypeCustom];
        weekNameLabel.titleLabel.text = [_weekNames objectAtIndex:i];
        [weekNameLabel setTitle:[_weekNames objectAtIndex:i] forState:UIControlStateNormal];
        [weekNameLabel setFrame:CGRectMake(originX+(cellWidth*(i%columns)), originY+cellHeight, cellWidth-cellMargin, cellHeight-cellMargin)];
        [weekNameLabel setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
        [weekNameLabel.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:fontSize]];
        weekNameLabel.userInteractionEnabled = NO;
        [self addSubview:weekNameLabel];
    }
    
    //月份变化通知
    //[NSThread detachNewThreadSelector:@selector(change) toTarget:self withObject:nil];
    
    
    //设置本月日期
    for (NSInteger i= 0; i<monthLength; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i+1;
        button.titleLabel.text = [NSString stringWithFormat:@"%d",i+1];
        [button setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
        [button setTitleColor:sa_color(50, 1.0) forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:fontSize]];
        [button addTarget:self action:@selector(tappedDate:) forControlEvents:UIControlEventTouchUpInside];
        NSInteger offsetX = (cellWidth*((i+weekday)%columns));
        NSInteger offsetY = (cellHeight *((i+weekday)/columns));
        [button setFrame:CGRectMake(originX+offsetX, originY+cellHeight*2+offsetY, cellWidth-cellMargin, cellHeight-cellMargin)];
        
        //边框圆
        button.layer.masksToBounds =  YES;
        button.layer.cornerRadius = button.bounds.size.width/2;
        
        //当天日期
        if(i+1 ==_selectedDate && components.month == _selectedMonth && components.year == _selectedYear)
        {
            [button setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
            [button setBackgroundColor:CalendarView_ClickColor];
            [button.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:fontSize-1]];
             button.titleLabel.numberOfLines = 0;
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
           
        }
        [self addSubview:button];
        //对外开放扩展
        [self extrlCell:button forYear:components.year forMonth:components.month forDay:i+1];
    }
    
    //设置上个月日期
    NSDateComponents *previousMonthComponents = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
    previousMonthComponents.month -=1;
    NSDate *previousMonthDate = [gregorian dateFromComponents:previousMonthComponents];
    NSRange previousMonthDays = [c rangeOfUnit:NSDayCalendarUnit
                   inUnit:NSMonthCalendarUnit
                  forDate:previousMonthDate];
    NSInteger maxDate = previousMonthDays.length - weekday;
    
    
    for (int i=0; i<weekday; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        int day = maxDate+i+1;
        button.titleLabel.text = [NSString stringWithFormat:@"%d",day];
        [button setTitle:[NSString stringWithFormat:@"%d",maxDate+i+1] forState:UIControlStateNormal];
        NSInteger offsetX = (cellWidth*(i%columns));
        NSInteger offsetY = (cellHeight *(i/columns));
        [button setFrame:CGRectMake(originX+offsetX, originY+cellHeight*2+offsetY, cellWidth-cellMargin, cellHeight-cellMargin)];

        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:fontSize]];
        [button setEnabled:NO];
        
        //对外开放扩展
        //[self extrlCell:button forYear:components.year forMonth:components.month forDay:day];
        [self addSubview:button];
    }
    
    //设置下月日期
    if(remainingDays >0){
        for (int i=remainingDays; i<columns; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            int day = (i+1)-remainingDays;
            button.titleLabel.text = [NSString stringWithFormat:@"%d",day];
            [button setTitle:[NSString stringWithFormat:@"%d",(i+1)-remainingDays] forState:UIControlStateNormal];
            NSInteger offsetX = (cellWidth*((i) %columns));
            NSInteger offsetY = (cellHeight *((monthLength+weekday)/columns));
            [button setFrame:CGRectMake(originX+offsetX, originY+cellHeight*2+offsetY, cellWidth-cellMargin, cellHeight-cellMargin)];
            
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [button.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:fontSize]];
            [button setEnabled:NO];
            //对外开放扩展
          // [self extrlCell:button forYear:components.year forMonth:components.month forDay:day];
            
            [self addSubview:button];
        }
    }
    
    
    UILabel *lineA = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 1)];
    lineA.backgroundColor = sa_color(236, 1.0);
    [self addSubview:lineA];
    
    UILabel *lineB = [[UILabel alloc]initWithFrame:CGRectMake(0, self.frame.size.height-1, self.frame.size.width, 1)];
    lineB.backgroundColor = sa_color(236, 1.0);
    [self addSubview:lineB];
    
    //月份改变通知
    [self change];
}


-(IBAction)tappedDate:(UIButton *)sender
{
    if (self.enabled==NO) return;
    gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
    if(!(_selectedDate == sender.tag && _selectedMonth == [components month] && _selectedYear == [components year]))
    {
        if(_selectedDate != -1)
        {
            UIButton *previousSelected =(UIButton *) [self viewWithTag:_selectedDate];
            [previousSelected setBackgroundColor:[UIColor clearColor]];
            [previousSelected setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        
        [sender setBackgroundColor:CalendarView_ClickColor];
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
        components.day = sender.tag;
        _selectedMonth = components.month;
        _selectedYear = components.year;
        _selectedDate = sender.tag;
        NSDate *clickedDate = [gregorian dateFromComponents:components];
        
        //日期选择回调
        if(self.delegate!=nil && [self.delegate respondsToSelector:@selector(selectedCell:forDate:)]){
            [self.delegate selectedCell:sender forDate:clickedDate];
        }
    }
}

-(void)swipeleft:(UISwipeGestureRecognizer*)gestureRecognizer
{
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
    components.day = 1;
    components.month += 1;
    self.calendarDate = [gregorian dateFromComponents:components];
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;//间隔的时间
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; ;
    animation.type = kCATransitionPush;//设置上面4种动画效果
    animation.subtype = kCATransitionFromRight;//设置动画的方向，有四种，分别为kCATransitionFromRight、kCATransitionFromLeft、kCATransitionFromTop、kCATransitionFromBottom
    [self.layer addAnimation:animation forKey:@"animationID"];
    [self setNeedsDisplay];
    //[self change];
}

-(void)swiperight:(UISwipeGestureRecognizer*)gestureRecognizer
{
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
    components.day = 1;
    components.month -= 1;
    self.calendarDate = [gregorian dateFromComponents:components];
//    [UIView beginAnimations:@"animationID" context:nil];
//    [UIView setAnimationDuration:0.5f]; //动画时长
//    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown  forView:self cache:YES]; //给视图添加过渡效果
//    [self setNeedsDisplay];
//    //在这里写你的代码.
//    [UIView commitAnimations]; //提交动画
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3f;//间隔的时间
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; ;
    animation.type = kCATransitionPush;//设置上面4种动画效果
    animation.subtype = kCATransitionFromLeft;//设置动画的方向，有四种，分别为kCATransitionFromRight、kCATransitionFromLeft、kCATransitionFromTop、kCATransitionFromBottom
    [self.layer addAnimation:animation forKey:@"animationID"];
    [self setNeedsDisplay];
    //[self change];
}

-(void)change{
    //日期选择回调
    if(self.delegate!=nil && [self.delegate respondsToSelector:@selector(changeMonth:)]){
        [self.delegate changeMonth:self.calendarDate];
    }
}

//日历翻页到上月
-(void)lastMonth{
    [self swiperight:nil];
}

//日历翻页到下月
-(void)nextMonth{
    [self swipeleft:nil];
}

//日历定位到当天
-(void)toDay{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.calendarDate = [NSDate date];
    [UIView transitionWithView:self
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^ { [self setNeedsDisplay]; }
                    completion:nil];
}


-(void)setCalendarParameters
{
    if(gregorian == nil)
    {
        gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.calendarDate];
        _selectedDate  = components.day;
        _selectedMonth = components.month;
        _selectedYear = components.year;
    }
}





@end
